package cn.com.jdyun.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.com.jdyun.mapper.ext.ExtSysConfigMapper;
import cn.com.jdyun.pojo.SysConfig;
import cn.com.jdyun.service.TransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;

import cn.com.jdyun.dto.GainsDTO;
import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.mapper.ext.ExtGainsMapper;
import cn.com.jdyun.pojo.Gains;
import cn.com.jdyun.pojo.LockCoin;
import cn.com.jdyun.pojo.UserWallet;
import cn.com.jdyun.service.GainsService;
import cn.com.jdyun.service.LockCoinService;
import cn.com.jdyun.service.MessageService;
import cn.com.jdyun.service.SysConfigService;
import cn.com.jdyun.service.UserWalletService;
import cn.com.jdyun.util.ConfigParam;
import cn.com.jdyun.util.Constant;
import cn.com.jdyun.util.RedisUtil;

@Service
public class GainsServiceImpl implements GainsService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private ExtGainsMapper gainsMapper;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private LockCoinService lockCoinService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private TransferService transferService;
    @Autowired
    private ExtSysConfigMapper sysConfigMapper;

    @Transactional(readOnly = true)
    @Override
    public Gains queryCurBalance(String date, String userId,String coinType) throws BdexGatewayException {
        return gainsMapper.selectByDateAndUserId(date, userId,coinType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Gains mining(String date, UserWallet wallet) throws BdexGatewayException {
        //判断用户属于微挖矿还是强挖矿
        if (wallet == null) {
            return null;
        }
        String userId = wallet.getUserId();

        //判断当天是否已经收取了矿
        Gains gains = queryCurBalance(date, userId,wallet.getCoinType());
        if (gains != null) {
            return gains;
        }

        BigDecimal lockedCoin = wallet.getLockedCoin() == null ? BigDecimal.valueOf(0) : wallet.getLockedCoin();

        SysConfig smallMinerConfig = sysConfigMapper.selectByCode(Constant.smallMiner);
        SysConfig texSmallMinerConfig = sysConfigMapper.selectByCode(Constant.texSmallMiner);
        SysConfig largeMiningMachineConfig = sysConfigMapper.selectByCode(Constant.largeMiningMachine);
        SysConfig texLargeMiningMachineConfig = sysConfigMapper.selectByCode(Constant.texLargeMiningMachine);
        BigDecimal cp = lockedCoin;
        if (wallet.getCoinType().equals(Constant.COINTYPE_SSSP)) {
            if (cp.subtract(new BigDecimal(smallMinerConfig.getInitValue())).doubleValue() < 0) {
                //不能挖矿
                return gains;
            }
        } else if (wallet.getCoinType().equals(Constant.COINTYPE_TEX)) {
            if (cp.subtract(new BigDecimal(texSmallMinerConfig.getInitValue())).doubleValue() < 0) {
                //不能挖矿
                return gains;
            }
        } else {
            throw new BdexGatewayException("挖矿币种参数错误!");
        }

        BigDecimal rate = null;
        if (wallet.getCoinType().equals(Constant.COINTYPE_SSSP)) {
            if (cp.subtract(new BigDecimal(smallMinerConfig.getInitValue())).doubleValue() >= 0 && cp.subtract(new BigDecimal(largeMiningMachineConfig.getInitValue())).doubleValue() < 0) {
                //微挖矿
                rate = Constant.gainsMini();
            } else if (cp.subtract(new BigDecimal(largeMiningMachineConfig.getInitValue())).doubleValue() >= 0) {
                //强挖矿
                rate = Constant.gainsStrong();
            }
        }else if (wallet.getCoinType().equals(Constant.COINTYPE_TEX)) {
            if (cp.subtract(new BigDecimal(texSmallMinerConfig.getInitValue())).doubleValue() >= 0 && cp.subtract(new BigDecimal(texLargeMiningMachineConfig.getInitValue())).doubleValue() < 0) {
                //微挖矿
                rate = Constant.gainsMini();
            } else if (cp.subtract(new BigDecimal(texLargeMiningMachineConfig.getInitValue())).doubleValue() >= 0) {
                //强挖矿
                rate = Constant.gainsStrong();
            }
        } else {
            throw new BdexGatewayException("挖矿币种参数错误!");
        }

        //BigDecimal balance = sysConfigService.miningPoolAmount(rate, userId);
        //当日锁仓能产生的收益
        BigDecimal balance = cp.multiply(rate).setScale(6, BigDecimal.ROUND_HALF_DOWN);

        if (balance.doubleValue() <= 0) {
            return gains;
        }
        if(wallet.getCoinType().equals(Constant.COINTYPE_SSSP)) {
            sysConfigService.changeConfigValue(ConfigParam.MINER_POOL_AMOUNT, balance.multiply(BigDecimal.valueOf(-1)).toString(), userId);
        } else if(wallet.getCoinType().equals(Constant.COINTYPE_TEX)){
            sysConfigService.changeConfigValue(ConfigParam.MINER_POOL_AMOUNT_TEX, balance.multiply(BigDecimal.valueOf(-1)).toString(), userId);
        }

        Date curDate = new Date();
        gains = new Gains();
        gains.setDate(date);
        gains.setTimes(0);
        gains.setUserId(userId);
        gains.setVested("0");
        gains.setCoinType(wallet.getCoinType());
        gains.setCreateTime(curDate);
        gains.setUpdateTime(curDate);
        BigDecimal bd = new BigDecimal(gains.getVested());


        bd = bd.add(balance).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        gains.setVested(bd.toString());
        gains.setRate(rate.toString());
        gains.setTimes(gains.getTimes() + 1);
        gains.setUpdateTime(curDate);
        if (gains.getId() == null) {
            gainsMapper.insert(gains);
        } else {
            gainsMapper.updateByPrimaryKeySelective(gains);
        }
        List<LockCoin> lockList = new ArrayList<>();
        //修改用户挖矿所得
        if(wallet.getCoinType().equals(Constant.COINTYPE_SSSP)) {
            userWalletService.updateMiningReward(userId, Constant.COINTYPE_SSSP, balance.toString());
            //修改每笔锁仓所得(去除释放完毕的锁仓记录)
            lockList = lockCoinService.selectUserLockCoin1(userId, Constant.COINTYPE_SSSP);
        }else if(wallet.getCoinType().equals(Constant.COINTYPE_TEX)) {
            userWalletService.updateMiningReward(userId, Constant.COINTYPE_TEX, balance.toString());
            //修改每笔锁仓所得(去除释放完毕的锁仓记录)
            lockList = lockCoinService.selectUserLockCoin1(userId, Constant.COINTYPE_TEX);
        }else{
            throw new BdexGatewayException("挖矿币种参数错误!");
        }

        BigDecimal cur = null;
        if(lockList!=null && lockList.size()>0){
            for (LockCoin lc : lockList) {
                BigDecimal result = balance.multiply(lc.getLockCoinAmount()).setScale(6, BigDecimal.ROUND_HALF_DOWN);
                result = result.divide(lockedCoin, 6).setScale(6, BigDecimal.ROUND_HALF_DOWN);
                cur = result;
                lc.setIncome(cur);
                lc.setUpdateTime(curDate);
//            lc.setLockCoinAmount(lc.getLockCoinAmount().subtract(cur));
                lockCoinService.updateByPrimaryKeySelective(lc);
            }
        }
//        //查询比特宝信息
//        UserWallet userWallet = transferService.inqueryLockedCoinAmount(userId, Constant.COINTYPE_SSSP);
//        userWallet.setAsset(new BigDecimal(userWallet.getAsset()).add(balance).setScale(6, BigDecimal.ROUND_HALF_DOWN)+"");
//        userWallet.setBalance(new BigDecimal(userWallet.getBalance()).add(balance).setScale(6, BigDecimal.ROUND_HALF_DOWN)+"");
//        userWallet.setMingCoin(balance+"");
//        userWallet.setUpdateTime(new Date());
//        userWalletService.updateWalletCoinAmount(userWallet);
        if(wallet.getCoinType().equals(Constant.COINTYPE_SSSP)) {
            //新增一条发送收益消息
            messageService.insertUserMessage(userId, "挖矿收益", "您当前锁仓：" + cp + Constant.COINTYPE_SSSP + ", 日收益率：" + rate, balance.toString(), Constant.COINTYPE_SSSP, "1");
        }else if(wallet.getCoinType().equals(Constant.COINTYPE_TEX)) {
            //新增一条发送收益消息
            messageService.insertUserMessage(userId, "挖矿收益", "您当前锁仓：" + cp + Constant.COINTYPE_TEX + ", 日收益率：" + rate, balance.toString(), Constant.COINTYPE_TEX, "1");
        }else{
            throw new BdexGatewayException("挖矿币种参数错误!");
        }


        return gains;
    }

    @Transactional(readOnly = true)
    @Override
    public Page<Gains> pageData(String userId) throws BdexGatewayException {
        return gainsMapper.pageData(userId);
    }

    @Override
    public List<GainsDTO> queryPartnerRelation(String userId, String coinType, String date) {
        return gainsMapper.queryPartnerRelation(userId, coinType, date);
    }
}
